const db = wx.cloud.database()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    cinemaInfoList: [],
    showList: [],
    coll: 'cinema',
    inputValue: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    
  },

  onShow() {
    // 获取当前小程序的页面栈     
    let pages = getCurrentPages()
    // 数组中索引最大的页面--当前页面  
    let currentPage = pages[pages.length-1]
    var options = currentPage.options
    var cinemaInfoList = []

    var that = this
    db.collection('cinema').get().then(res => {
      for (let idx in res.data) {
        var articleObj = {
          id: res.data[idx]._id,
          name: res.data[idx].funTitle,
          address: res.data[idx].place,
          label: res.data[idx].label
          // image: res.data[idx].image
        }
        cinemaInfoList.push(articleObj)
      }

      that.setData({
        cinemaInfoList: JSON.parse(JSON.stringify(cinemaInfoList)),
        showList: JSON.parse(JSON.stringify(cinemaInfoList)),
        inputValue: ''
      })
    })
  },

  search(e) {
    var word = e.detail.value
    var showList = []
    for (const v of this.data.cinemaInfoList) {
      if (v.name.search(word) !== -1) {
        showList.push(JSON.parse(JSON.stringify(v)))
      }
    }

    this.setData({showList: showList})
  },

  cancelSearch() {
    this.setData({
      inputValue: '',
      showList: JSON.parse(JSON.stringify(this.data.cinemaInfoList))
    })
  },

  copy(e) {
    var content = e.currentTarget.dataset.content
    wx.setClipboardData({
      data: content,
      success(res){
        wx.showToast({
          title: '复制成功',
          duration: 1000
        })
      },
      fail(res) {
        console.log(res)
      }
    })
  },

  createArticle() {
    wx.navigateTo({
      url: `/pages/edit_cinema/edit_cinema`,
    })
  },

  editArticle(e) {
    var index = e.currentTarget.dataset.index
    var id = this.data.showList[index].id
    wx.navigateTo({
      url: `/pages/edit_cinema/edit_cinema?id=${id}`,
    })
  },

  async deleteArticle(e) {
    var flag = false
    await wx.showModal({
      title: '提示',
      content: '确认要删除吗'
    }).then(res => {
      if (res.confirm) {
        flag = true
      }
    })

    if (!flag) {
      return
    }

    var that = this
    var index = e.currentTarget.dataset.index
    var cinemaInfoList = this.data.cinemaInfoList
    var showList = this.data.showList

    await db.collection(that.data.coll).where({
      _id: showList[index].id
    }).remove().then(res => {
      var deleteIdx = 0
      while (deleteIdx < cinemaInfoList.length) {
        if (cinemaInfoList[deleteIdx].id === showList[index].id) {
          break
        }

        ++deleteIdx
      }
      showList.splice(index, 1)
      cinemaInfoList.splice(deleteIdx, 1)
      that.setData({
        showList: showList,
        cinemaInfoList: cinemaInfoList
      })
    })

    wx.showToast({
      title: '删除成功',
      icon: 'success',
      duration: 1000
    })
  }
})